package cn.yuxiaoyuan.system.service.impl;

import cn.yuxiaoyuan.base.service.impl.BaseServiceImpl;
import cn.yuxiaoyuan.system.domain. Role;
import cn.yuxiaoyuan.system.mapper. RoleMapper;
import cn.yuxiaoyuan.system.query. RoleQuery;
import cn.yuxiaoyuan.system.service. RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl< Role> implements  RoleService {
    @Autowired
    private  RoleMapper roleMapper;
    @Override
    public List<Role> queryPage( RoleQuery roleQuery) {
        List<Role> roles = roleMapper.queryPage(roleQuery);
        for (Role role : roles) {
            role.setMenus(roleMapper.selectMenusIdByRoleId(role.getId()));
            role.setPermissions(roleMapper.selectPerIdByRoleId(role.getId()));
        }
        return roles;
    }

    @Override
    @Transactional
    public void add(Role role) {
        Role r = roleMapper.findRoleByRole(role);
        if(r == null){
            super.add(role);
        }else {
            throw new RuntimeException(role.getSn()+":该角色编码已存在");
        }
        //保存权限
        roleMapper.savePermissions(role.getId(),role.getPermissions());
        //保存菜单
        roleMapper.saveMenus(role.getId(),role.getMenus());
    }

    @Transactional
    @Override
    public void update(Role role) {
        Role r = roleMapper.findRoleByRole(role);
        if(r == null){
            super.update(role);
        }else {
            throw new RuntimeException(role.getSn()+":该角色编码已存在");
        }
        //删除权限
        roleMapper.deletePreByRoleId(role.getId());
        //删除菜单
        roleMapper.deleteMenuByRoleId(role.getId());
        //保存权限
        roleMapper.savePermissions(role.getId(),role.getPermissions());
        //保存菜单
        roleMapper.saveMenus(role.getId(),role.getMenus());
    }
}
